<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="台账类型:" prop="storeType">
        <el-select v-model="query.storeType" filterable clearable placeholder="请选择" @change="storeTypeChange">
          <el-option
            v-for="(item,index) in ledgerList"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据类型:" prop="reBillType">
        <el-select v-model="query.reBillType" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in reBillTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规格型号:" prop="specCode">
        <el-select v-model="query.specCode" :clearable="true" filterable placeholder="请选择">
          <el-option
            v-for="item in typeList"
            :key="item.specCode"
            :label="item.specName"
            :value="item.specCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态:" prop="gdStatus">
        <el-select v-model="query.gdStatus" :clearable="true" filterable placeholder="请选择">
          <el-option label="重瓶" :value="1" />
          <el-option label="空瓶" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库名称:" prop="storeId">
        <el-select v-model="query.storeId" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" label="时间:" clearable>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
  </div>
</template>

<script>
  import { invenInOrOut, invenQuerySpec, repertoryStore } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import dayjs from 'dayjs'
  export default {
    name: 'ledger-stations',
    data() {
      return {
        actionColWidth: 80,
        date: [dayjs().format('YYYY-MM-DD') + ' ' + '00:00:00', dayjs().format('YYYY-MM-DD') + ' ' + '23:59:59'],
        query: {
          storeType: '',
          gdStatus: '',
          specCode: '',
          reBillType: ''
        },
        typeList: [],
        ledgerList: [
          { label: '全部', value: '' },
          { label: '出库', value: 1 },
          { label: '入库', value: 2 },
          { label: '盘点', value: 3 }
        ],
        reBillTypeListALL: [
          { label: '调拨出库', value: 1 },
          { label: '调拨入库', value: 2 },
          { label: '领瓶出库', value: 3 },
          { label: '领瓶入库', value: 4 },
          { label: '还瓶出库', value: 5 },
          { label: '还瓶入库', value: 6 },
          { label: '订单配送', value: 7 },
          { label: '退瓶消单入库', value: 8 },
          { label: '预约退瓶', value: 9 },
          { label: '退瓶出库', value: 10 },
          { label: '出库单出库', value: 11 },
          { label: '入库单入库', value: 12 },
          { label: '盘盈', value: 13 },
          { label: '盘亏', value: 14 },
          { label: '退货出库', value: 15 },
          { label: '退货入库', value: 16 },
          { label: '计划充装单出库', value: 17 },
          { label: '计划充装单入库', value: 18 }
        ],
        reBillTypeList: [],
        storeMap: [],
        tableData: {
          total: 0,
          data: [],
          column: [
            {
              type: 'index'
            },
            {
              prop: 'storeName',
              label: '仓库名称',
              minWidth: 160
            },
            {
              prop: 'storeType',
              label: '台账类型',
              minWidth: 80,
              render: (h, { row }) => (
            <span>
              {row.storeType ? formatColumnMap(this.ledgerList, 'value', row.storeType, 'label')
                : ''}
            </span>
          )
            },
            {
              prop: 'specName',
              minWidth: 80,
              label: '规格型号'
            },
            {
              prop: 'gdStatus',
              minWidth: 60,
              label: '状态',
              formatter: (row) => {
                return row.gdStatus ? row.gdStatus === 1 ? '重瓶' : row.gdStatus === 2 ? '空瓶' : '' : ''
              }
            },
            {
              prop: 'reBillType',
              label: '单据类型',
              minWidth: 110,
              render: (h, { row }) => (
            <span>
              {row.reBillType ? formatColumnMap(this.reBillTypeListALL, 'value', row.reBillType, 'label')
                : ''}
            </span>
          )
            },
            {
              prop: 'gdCount',
              label: '数量',
              render: (h, { row, $index }) => (
                <div>
                  { row.reBillType === 14 ? <el-link type='danger' underline={false} size='mini'> - {row.gdCount}</el-link>
                  : row.reBillType === 13 ? <el-link type='danger' underline={false} size='mini'> + {row.gdCount}</el-link>
                  : row.storeType === 2 ? <span> + {row.gdCount}</span>
                    : row.storeType === 1 ? <span> - {row.gdCount}</span>
                  : row.gdCount}
                </div>
                )
            },
            {
              prop: 'reBillCode',
              label: '关联单号'
            },
            {
              prop: 'operator',
              label: '操作人'
            },
            {
              prop: 'operatorTime',
              label: '操作时间',
              minWidth: 160,
              render: (h, { row }) => <span>{ row.operatorTime && parseTime(row.operatorTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            }
          ]
        }
      }
    },
    async created() {
      this.initStoreMap()
      this.storeTypeChange()
      this.getTypeList()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          params: { ...this._getQuery(this.query) },
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.params.operatorTime = parseTime(this.date[0], '{y}-{m}-{d} {h}:{i}:{s}')
          query.params.operatorTimeEnd = parseTime(this.date[1], '{y}-{m}-{d} {h}:{i}:{s}')
        }
        const res = await invenInOrOut(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async getTypeList() {
        const res = await invenQuerySpec({})
        this.typeList = res.data
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      reset() {
        this.query = {
          storeType: '',
          gdStatus: '',
          specCode: '',
          reBillType: ''
        }
        this.date = [dayjs().format('YYYY-MM-DD') + ' ' + '00:00:00', dayjs().format('YYYY-MM-DD') + ' ' + '23:59:59']
        this.$refs.form.resetFields()
      },
      storeTypeChange() {
        this.query.reBillType = ''
        this.reBillTypeList = this.reBillTypeListALL
        switch (this.query.storeType) {
        case 1:
          this.reBillTypeList = this.reBillTypeList.filter(item => item.value === 1 || item.value === 11 || item.value === 15 || item.value === 3 || item.value === 17 || item.value === 10)
          break
        case 2:
          this.reBillTypeList = this.reBillTypeList.filter(item => item.value === 2 || item.value === 12 || item.value === 6 || item.value === 16 || item.value === 8 || item.value === 18)
          break
        case 3:
          this.reBillTypeList = this.reBillTypeList.filter(item => item.value === 13 || item.value === 14)
          break
        default:
          break
        }
      },
      async initStoreMap() {
        const params = {
          reType: 4
        }
        const res = await repertoryStore(params)
        this.storeMap = res.data
        // if (res.data.length > 0) this.query.storeId = res.data[0].storeId
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
